package com.sks.web.action.district;

import java.util.ArrayList;

import java.util.LinkedHashMap;
import java.util.List;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.stereotype.Controller;

import com.sks.bean.PageView;

import com.sks.bean.pojo.Building;
import com.sks.bean.pojo.Favorites;
import com.sks.bean.pojo.House;
import com.sks.bean.uploadfile.UploadFile;
import com.sks.service.house.AreaService;
import com.sks.service.house.BuildingService;
import com.sks.service.house.FavoritesService;
import com.sks.service.house.HouseService;
import com.sks.service.house.HouseTypeService;
import com.sks.service.house.MetroService;
import com.sks.service.house.MetroStationService;
import com.sks.service.house.PropertyTypeService;
import com.sks.service.uploadfile.UploadFileService;
import com.sks.utils.WebUtil;
import com.sks.web.action.BasicAction;
import com.sks.web.formbean.house.HouseForm;

/**
 * 小区详细信息功能
 * @author yuanjiayuan
 *
 */
@Controller("/sks/districtInfo")
public class DistrictInfoAction extends BasicAction{
	
	@Resource(name = "areaServiceBean") private AreaService areaService;
	@Resource(name = "houseServiceBean") private HouseService service;
	@Resource(name = "metroStationServiceBean") private MetroStationService metroStationService;
	@Resource(name = "metroServiceBean") private MetroService metroService;
	@Resource(name = "uploadFileServiceBean")private UploadFileService uploadFileService;
	@Resource(name = "buildingServiceBean")	private BuildingService buildingService;
	@Resource(name = "propertyTypeServiceBean") private PropertyTypeService propertyTypeService;
	@Resource(name = "houseTypeServiceBean") private HouseTypeService houseTypeService;
	@Resource(name = "favoritesServiceBean") private FavoritesService favoritiesService;
	
	/**
	 * 小区概况
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward base(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		  common(mapping,form,request,response);
		  checkCollect(request);
	      return mapping.findForward("base");
	            
	}
	
	/**
	 * 小区照片
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward photo(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		  common(mapping,form,request,response);
		  checkCollect(request);
		  Building building = buildingService.find(Integer.parseInt(request.getParameter("buildingId")));
		  request.setAttribute("photo", building);
	      return mapping.findForward("photo");
	            
	}
	
	/**
	 * 小区浏览大张照片
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward photoBrowse(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		  common(mapping,form,request,response);
		  Building building = buildingService.find(Integer.parseInt(request.getParameter("buildingId")));
		  checkCollect(request);
		  List<UploadFile> pic = new ArrayList<UploadFile>(0);
		  StringBuffer sb = new StringBuffer();

		  pic = building.getPictures();		//获取小区图片
		  
		  for(int i=0;i<pic.size();i++){		 
				sb.append(pic.get(i).getPath()+'/'+pic.get(i).getName()+'.'+pic.get(i).getExtension());  
				if(pic.size()-1 != i){
					sb.append(",");
				}
		  }
		  
		  request.setAttribute("pictrue", sb);

		  return mapping.findForward("photoBrowse");
	            
	}
	
	/**
	 * 小区出租房源
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward houseRentList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		  common(mapping,form,request,response);
		  checkCollect(request);
	      return mapping.findForward("houseRentList");
	            
	}
	
	/**
	 * 小区出售房源
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward houseSaleList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		  common(mapping,form,request,response);
		  checkCollect(request);
	      return mapping.findForward("houseSaleList");
	            
	}
	
	/**
	 * 小区周边情况
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward detail(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		  common(mapping,form,request,response);
		  checkCollect(request);
	      return mapping.findForward("detail");
	            
	}

	/**
	 * 小区地图
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward map(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		  common(mapping,form,request,response);
		  checkCollect(request);
	      return mapping.findForward("map");
	            
	}
	
	/**
	 * 小区收藏
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unused")
	private ActionForward favorites(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		WebUtil.getUsers(request).getUserId();
		checkCollect(request);
		return mapping.findForward("favorites");
	}
	
	/**
	 * 公共信息
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public void common(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		
		setBaseData(request);
		
		if (WebUtil.getUsers(request) != null) { // 判断是否用户已登录,用于前台收藏功能
			request.setAttribute("user", WebUtil.getUsers(request).getUserId());
		} else {
			request.setAttribute("user", "nobody");
		}
		houseList(mapping, form, request, response);// 返回小区房源

		Building building = buildingService.find(Integer.parseInt(request.getParameter("buildingId")));

		request.setAttribute("building", building);
	}
	
	/**
	 * 小区房源
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public void houseList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response){
	      HouseForm formbean = (HouseForm) form;
	      StringBuffer sb = new StringBuffer(" o.houseStatus = '" + House.HOUSE_STATUS_PUBLISHED + "'");
	      List<Object> params = new ArrayList<Object>();
	      
	      int firstindex = formbean.getChangeOrderBy() ? 1 : formbean.getPage();
	      
	      if(request.getParameter("buildingId") != null){
	    	  sb.append(" and o.building.buildingId = ?");
	    	  params.add(Integer.parseInt(request.getParameter("buildingId")));
	      }

	      if("Buy".equals(request.getParameter("isRent")) ){
	    	  sb.append(" and o.transaStatus = ?");
	    	  params.add(1);
	      }else {
	    	  sb.append(" and o.transaStatus in (?, 2)");
	    	  params.add(0);
	      }
	      if (null != formbean.getMenuName()) {
	    	  if ("houseListBuy".equals(formbean.getMenuName())) {
	    		  sb.append(" and o.transaStatus in (?, 2)");
	    		  params.add(1);
	    	  } else if ("houseListRent".equals(formbean.getMenuName())) {
	    		  sb.append(" and o.transaStatus in (?, 2)");
	    		  params.add(0);
	    	  }
	    	  
	    	  if (null != formbean.getMaxPrice() || null != formbean.getMinPrice()) {
	        	  setPriceRange(request,formbean, sb, params);
	          }
	      }
	      if (null != formbean.getHouseTypeId()) {
	    	  sb.append(" and o.houseType.houseTypeId = ?");
	    	  params.add(formbean.getHouseTypeId());
	      }
	      if (null != formbean.getPropertyTypeId()) {
	    	  sb.append(" and o.propertyType.propertyTypeId = ?");
	    	  params.add(formbean.getPropertyTypeId());
	      }
	      
	      LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
	      if (null != formbean.getOrderBy()) {
	  		  String[] ss = formbean.getOrderBy().split("_");
	  		  if (ss.length >= 2) {
	  			  orderby.put(ss[0], ss[1]);
	  		  }
	      }
	      orderby.put("isHot", "desc");
	      
	      PageView<House> pv = new PageView<House>(formbean.getPageSize(), firstindex);
	      pv.setQueryResult(service.getScrollData(pv.getFirstResult(), pv.getMaxresult(), sb.toString(), params.toArray(), orderby));
	      
	      request.setAttribute(PAGEVIEW, pv);
	}
	
	/**
	 * 价格过滤
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	private void setPriceRange(HttpServletRequest request,HouseForm formbean, StringBuffer sb, List<Object> params) {
		if ("Buy".equals(request.getParameter("isRent"))) {
			if (null != formbean.getMinPrice()) {
				sb.append(" and o.salePrice >= ?");
				params.add(Double.parseDouble(formbean.getMinPrice().toString()));
			}

			if (null != formbean.getMaxPrice()) {
				sb.append(" and o.salePrice < ?");
				params.add(Double.parseDouble(formbean.getMaxPrice().toString()));
			}
		} else if ("Rent".equals(request.getParameter("isRent"))) {
			if (null != formbean.getMinPrice()) {
				sb.append(" and o.rentPrice >= ?");
				params.add(Double.parseDouble(formbean.getMinPrice().toString()));
			}

			if (null != formbean.getMaxPrice()) {
				sb.append(" and o.rentPrice < ?");
				params.add(Double.parseDouble(formbean.getMaxPrice().toString()));
			}
		}
	}

	
	private void setBaseData(HttpServletRequest request) {
		      request.setAttribute("areaPageView", areaService.getScrollData().getResultlist());
		      request.setAttribute("metroStationPageView", metroStationService.getScrollData().getResultlist());
		      request.setAttribute("metroPageView", metroService.getScrollData().getResultlist());
		      request.setAttribute("uploadFilePageView", uploadFileService.getScrollData().getResultlist());
		      request.setAttribute("houseTypes", houseTypeService.getScrollData().getResultlist());
		      request.setAttribute("topAreas", areaService.findAreas(true, true));
		      request.setAttribute("propertyTypes", propertyTypeService.getScrollData().getResultlist());
	}
	
	private void checkCollect(HttpServletRequest request) {
		if (WebUtil.getUsers(request) != null) { // 判断是否用户已登录,用于前台收藏功能
			List<Object> params = new ArrayList<Object>();
			request.setAttribute("user", WebUtil.getUsers(request).getUserId());
			StringBuffer sb = new StringBuffer(" o.user.userId = " + WebUtil.getUsers(request).getUserId());
			sb.append(" and o.building.buildingId = ?");
			  params.add(Integer.parseInt(request.getParameter("buildingId")));
			PageView<Favorites> pv = new PageView<Favorites>(20, 0);
			pv.setQueryResult(favoritiesService.getScrollData(0, pv.getMaxresult(), sb.toString(), params.toArray(), null));
			if(pv.getTotalrecord()>0){
				request.setAttribute("isCollected", true);
			}
		} else {
			request.setAttribute("user", "nobody");
		}
	}
}
